<template>
  <a-card size="small" :bordered="false" title="个人信息">
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-col="{ xs: { span: 6 }, md: { span: 4 }, xl: { span: 2 } }"
      :wrapper-col="{ xs: { span: 18 }, md: { span: 12 }, xl: { span: 8 } }"
    >
      <a-form-item label="用户名">
        <a-input :value="userStore.userInfo.username" :disabled="true" />
      </a-form-item>
      <a-form-item label="真实姓名" name="realname">
        <a-input v-model:value="formData.realname" />
      </a-form-item>
      <a-form-item label="手机号" name="phone">
        <a-input v-model:value="formData.phone" />
      </a-form-item>
      <a-form-item label="邮箱" name="email">
        <a-input v-model:value="formData.email" />
      </a-form-item>
      <a-form-item
        :wrapper-col="{
          xs: { span: 18, offset: 6 },
          md: { span: 14, offset: 4 },
          xl: { span: 12, offset: 2 }
        }"
      >
        <a-button type="primary" :loading="loading" @click="onSubmit">
          <template #icon>
            <SaveOutlined />
          </template>
          <span v-if="!loading">提交</span>
          <span v-else>加载中...</span>
        </a-button>
        <a-button style="margin-left: 10px" @click="resetFields">
          <template #icon>
            <RedoOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-form>
  </a-card>
</template>
<script name="personalInfo" lang="ts" setup>
import { phoneValidator, realnameValidator } from "@/utils/validator";
import { updateUserInfo } from "@/api/public/personal";

const loading = ref<boolean>(false);
const userStore = useUserStore();

const formRef = ref();
const formData = reactive({
  realname: userStore.userInfo["realname"],
  phone: userStore.userInfo["phone"],
  email: userStore.userInfo["email"]
});
const formRules = {
  realname: [
    { required: true, trigger: "blur", message: "请输入真实姓名" },
    { validator: realnameValidator, trigger: "blur" }
  ],
  phone: [
    { required: true, trigger: "blur", message: "请输入手机号" },
    { validator: phoneValidator, trigger: "blur" }
  ]
};

const onSubmit = async (e: MouseEvent) => {
  e.preventDefault();

  formRef.value
    .validate()
    .then(() => {
      loading.value = true;
      updateUserInfo(formData)
        .then(() => {
          antdMessage.success("修改成功");
          userStore.getUserInfo();
        })
        .catch(error => {
          // console.log("error", error);
        })
        .finally(() => {
          loading.value = false;
        });
    })
    .catch(error => {
      //console.log(error);
    });
};

const resetFields = () => {
  formRef.value.resetFields();
};
</script>
